const express  = require ('express');
const pool = require('../pool');

const router = express.Router();
//
router.get('/queryById',(req,res,next)=>{
    let id  = req.query.id
    pool.query(`select * from essay where e_id=${id}`,(err,r)=>{
        if(err){
            return next(err)
        }
        if(r.length !=0){
            res.send({code:200,data:r})
        }
    })
})

router.get('/querAll',(req,res,next)=>{
    let page = (req.query.page -1 ) * 18;
    let pageCount = 18;
    pool.query(`select e_id,img,title,worker from essay limit ${page},${pageCount}`,(err,r)=>{
        if(err){
            return next(err)
        }
        pool.query('select count(*) from essay',(err,resp)=>{
            if(err){
                return next(err)
            }
            let pageSize = Math.ceil(resp.length/18);
            res.send({code:200,data:{data:r,pageSize}})
        })
    })
})

router.post('/add',(req,res,next)=>{
    let title = req.body.title; //标题
    let count =req.body.count; //内容
    let img = req.body.img;
    let worker = req.body.worker //作者
    let date = new Date();
    pool.query(`insert into essay values(null,?,?,?,?,?)`,[title,count,img,worker,date],(err,r)=>{
        if(err){
            return next(err)
        }
        res.send({code:200,msg:'添加成功',data:r})
    })
})

router.post('/dele',async(req,res,next)=>{
    let id = req.body.id 
    pool.query(`delete from essay where e_id=${id}`,(err,r)=>{
        if(err){
            return next(err)
        }
        res.send({code:200,msg:'删除成功'})
    })
})

router.post('/update',async (req,res,next)=>{
    // console.log("接口访问成功");
    let id = req.body.e_id; //文章iD
    let title = req.body.title;
    let count = req.body.count;
    let img = req.body.img;
    let worker = req.body.worker //作者
    let etime=req.body.etime
    pool.query(`update essay set title=?,count=?,img=?,worker=?,etime=? where e_id=${id}`,[title,count,img,worker,etime],(err,r)=>{
        if(err){
            return next(err)
        }
        if(r.length!=0){
            res.send({code:200,msg:'修改成功',r})
        }else{
            res.send({code:400,msg:'修改失败'})
        }
    }) 
})


//查询所有浏览量
router.get("/queryLook",async (req,res,next)=>{
      let sql="select sum(look) as sumld from essay"
      pool.query(sql,(err,r)=>{
         if(err){
          return next(err)
        }
         ressend({code:200,data:r})
     })
})
        //查询所有下载量
router.get("/queryDown",async (req,res,next)=>{
   let sql="select sum(down) as sumdd from essay"
      pool.query(sql,(err,r)=>{
         if(err){
           return next(err)
        }
        res.send({code:200,data:r})
    })
})



module.exports = router;